// pages/enterprise/enterpriseCont/enterpriseCont.js
var app = getApp();
import SDK from "../../../IMJS/NIM_Web_SDK_weixin_v6.2.0";
import {
    ajaxPost,
    showToast,
} from "../../../utils/util.js";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        WEBURL: app.globalData.WEBURL, // 背景图域名
        smallScrollTop: 0, // 房间聊天内容 当前滚动高度
        hallScrollTop: 0, // 大厅聊天内容 当前滚动高度
        scrollHeight: 0, // 聊天内容 总共高度
        contId: "", // 企业id
        hallRoomId: "",
        roomSource: {}, //房间信息
        firstTime: 0, ///倒计时
        hallRoomId: "", // 大厅聊天室 房间id
        smallNewsArr: [], //房间聊天室信息储存
        hallNewsArr: [], //房间聊天室信息储存
        userlist: [],
        textareaVal: "", // 简历备注

        noticeShow: true, // 公告是否显示 false=>不显示
        lobbyInviteTime: 0, // 推广消息剩余时间
        privacyVal: true, // 隐私控制 
        muted: true, // 麦克风是否静音 
        playVoice: false, // 播放声音是否静音 
        footerShow: true, // 操作与输入框切换
        inputValue: "", // 输入框内容
        emojiShow: false, // 表情是否显示 false=>不显示
        selectRoomVal: "small", //控制输入框失去焦点与否
        focusFlag: false, //控制输入框失去焦点与否
        emojiFlag: false, //emoji键盘标志位
        moreFlag: false, // 更多功能标志

        studentSource: {}, //学生信息保存
        popupShow: false, //学生信息保存
        popupVal: 1, //1 ==》 简历展示 2=》基本信息展示


        inviteVal: app.globalData.inviteVal, // 其他房间是否展示 false =》不展示 true =》展示
        restsShow: true, // 其他房间是否展示 false =》不展示 true =》展示
        companyListShow: false, // 其他房间 企业列表和学生列表 切换  false =》不展示 true =》展示
        companyListSource: [], // 公司列表
        studentListSource: [], // 公司列表
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 手机屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true
        });
        // 设置 scroll-view高度
        let windowHeight = wx.getSystemInfoSync().windowHeight; // 屏幕的高度
        let windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕的宽度
        this.setData({
            companyListHeight: (windowHeight * 750) / windowWidth - 46,
            scrollHeight: (windowHeight * 750) / windowWidth - 746 - 30,
            contId: options.id,
            hallRoomId: options.roomid
        });


    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            inviteVal: app.globalData.inviteVal
        })
        console.log('this.data.inviteVal', this.data.inviteVal);
        this.getSmallRoomConfig();
        this.hallRoomConfig();
        this.listenNetcallEvent();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        clearInterval(this.noticeTime);
        clearInterval(this.Heart);
        clearInterval(this.RoomQueue);
        /**
         * 推广倒计时
         */
        clearInterval(this.setLobbyInviteTime);
        wx.navigateBack();
        wx.setKeepScreenOn({
            keepScreenOn: false
        });
        console.log("-------->退出聊天室");
        app.globalData.hallRoom.disconnect();
        app.globalData.smallRoom.disconnect();
        app.globalData.netcall.leaveChannel().then(() => {
            // 清除上层UI逻辑
            console.log("-------->音频聊天室退出");
        });
        console.log('返回上一页');
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.Heart);
        clearInterval(this.RoomQueue);
        /**
         * 推广倒计时
         */
        clearInterval(this.setLobbyInviteTime);
        wx.setKeepScreenOn({
            keepScreenOn: true
        });
        console.log("-------->退出聊天室");
        app.globalData.hallRoom.disconnect();
        app.globalData.smallRoom.disconnect();
        app.globalData.netcall.leaveChannel().then(() => {
            // 清除上层UI逻辑
            console.log("-------->音频聊天室退出");
        });
    },
    /**
     * 
     * 获取企业房间信息 以及进入企业房间聊天室
     */
    getSmallRoomConfig(channelName) {
        let that = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
            company_uid: 0
        };
        if (!!channelName) {
            data.vroomid = channelName
        }
        ajaxPost("/meeting/roominfo", data, (res) => {
            if (res.code == 0) {
                that.setData({
                    roomSource: res.data,
                });
                /**
                 * 判断是否可以弹出公告窗口
                 */
                if (that.data.noticeShow) {
                    let viewHeight;
                    wx.createSelectorQuery().selectAll('.notice').boundingClientRect(function (rect) {
                        viewHeight = rect[0].height
                        that.setData({
                            scrollHeight: that.data.scrollHeight - (viewHeight * 2) - 40
                        })
                    }).exec()
                    this.noticeTime = setTimeout(() => {
                        that.setData({
                            scrollHeight: that.data.scrollHeight + (viewHeight * 2) + 40,
                            noticeShow: false,
                        })
                    }, app.globalData.noticeTimeNum);
                }
                if (res.data.is_hide == 2) {
                    var content = {
                        type: 'company',
                        privacyVal: 2,
                        nick: res.data.company_name,
                        text: '我有几个隐私问题要问这位同学，大家将暂时听不见我们的谈话，请大家稍等一下～',
                        account: res.data.company_logo,
                    };
                    that.setData({
                        smallNewsArr: [...that.data.smallNewsArr, content],
                    });
                    this.setData({
                        privacyVal: false,
                    })
                }
                if (!res.data.vroomid) {
                    that.newVoiceConfig();
                } else {
                    that.voiceConfig();
                }
                /**
                 * 清除心跳后重新心跳
                 */
                clearInterval(this.Heart);
                this.Heart = setInterval(() => {
                    this.getHeart();
                }, 1000);
                clearInterval(this.RoomQueue);
                this.getRoomQueue();
                this.RoomQueue = setInterval(() => {
                    this.getRoomQueue();
                }, 5000);
                that.smallRoomConfig();
            } else {
                showToast("error", res.msg);
            }
        });
    },
    /***
     * 加入企业音频聊天室
     */
    voiceConfig() {
        let that = this;
        let channelName = this.data.roomSource.vroomid;
        app.globalData.netcall.joinChannel({
                mode: 1,
                channelName: channelName,
                role: 0
            }).then(data => {
                console.error('加入音频房间成功');
                showToast('text', '加入音频房间成功')
                // 添加uid
                let userlist = Object.assign([], that.data.userlist);
                userlist.map(user => {
                    user.uid = data.accountUidMap[user.account];
                });
                that.setData({
                    beCalling: false,
                    loginUser: {
                        uid: data.uid,
                        cid: data.cid,
                        account: data.account
                    },
                    userlist,
                    accountToUidMap: data.accountUidMap,
                    streamNeedReconnect: true
                });
                that.livePusherContext = wx.createLivePusherContext();
            })
            .catch(error => {
                console.error(error);
                this.newVoiceConfig(true);

            });
        // })
    },
    /**
     * 判断没有vroomid 创建房间名称 并加入音频房间
     */
    newVoiceConfig(type) {
        console.error('type----->1', type);
        let that = this;
        let id = this.data.roomSource.company_uid
        let channelName = `sz-${id}-${new Date().getTime()}`;
        if (type) {
            channelName = this.data.roomSource.vroomid
        }
        app.globalData.netcall
            .createChannel({
                channelName: channelName
            })
            .then(data => {
                console.error('type----->2', type);
                if (type) {
                    that.voiceConfig()
                } else {
                    that.getSmallRoomConfig(channelName);
                }
            })
            .catch(function (error) {
                console.error('发生错误！', error);
            });

    },
    /**
     * 加入企业房间聊天室
     */
    smallRoomConfig() {
        let that = this;
        app.globalData.nim.getChatroomAddress({
            chatroomId: this.data.roomSource.roomid,
            done: getChatroomAddressDone
        });

        function getChatroomAddressDone(error, data) {
            app.globalData.smallRoom = SDK.Chatroom.getInstance({
                debug: false,
                appKey: app.globalData.appkey,
                token: app.globalData.wytoken,
                account: app.globalData.account,
                chatroomAddresses: data.address,
                chatroomId: data.chatroomId,
                onconnect: that.onChatroomConnect,
                onerror: that.onChatroomError,
                onwillreconnect: that.onChatroomWillReconnect,
                ondisconnect: that.onChatroomDisconnect,
                // 消息
                onmsgs: that.onChatroomMsgs
            });
        }
    },
    /**
     * 大厅聊天室加入
     */
    hallRoomConfig() {
        let that = this;
        app.globalData.nim.getChatroomAddress({
            chatroomId: this.data.hallRoomId,
            done: getChatroomAddressDone
        });

        function getChatroomAddressDone(error, data) {
            app.globalData.hallRoom = SDK.Chatroom.getInstance({
                debug: false,
                appKey: app.globalData.appkey,
                token: app.globalData.wytoken,
                account: app.globalData.account,
                chatroomAddresses: data.address,
                chatroomId: data.chatroomId,
                onconnect: that.onChatroomConnect,
                onerror: that.onChatroomError,
                onwillreconnect: that.onChatroomWillReconnect,
                ondisconnect: that.onChatroomDisconnect,
                // 消息
                onmsgs: that.onChatroomMsgs
            });
        }
    },

    /**
     * 返回指定uid组件的拉流操作上下文
     */
    _getPlayerComponent(uid) {
        const yunxinPlayer = this.selectComponent(`#yunxinplayer-${uid}`);
        return yunxinPlayer;
    },
    /**
     * 返回推流组件的操作上下文
     */
    _getPusherComponent() {
        const yunxinPusher = this.selectComponent(`#yunxin-pusher`);
        return yunxinPusher;
    },
    /**
     * 连接上服务器
     */
    onChatroomConnect(chatroomInfo) {
        if (chatroomInfo.chatroom.id == this.data.hallRoomId) {
            showToast('text', '加入大厅聊天室成功')
            console.log('加入大厅聊天室成功');
        } else {
            console.log('加入房间聊天室成功');
            showToast('text', '加入房间聊天室成功')
        }
        console.log("连接上服务器", chatroomInfo);
    },
    /**
     * 发生错误
     */
    onChatroomError(error, obj) {
        clearTimeout(this.pageTimer);
        this.pageTimer = setTimeout(() => {
            wx.showToast({
                title: "连接已断开,即将返回",
                duration: 2000,
                success: function () {
                    wx.redirectTo({
                        url: "/pages/enterprise/home/home"
                    });
                }
            });
        }, 200);
    },
    /**
     * 即将重连
     */
    onChatroomWillReconnect(obj) {
        console.log(
            `onwillreconnect-${app.globalData.reconnectionAttempts}`,
            obj
        );
    },
    /**
     * 已经断开连接
     */
    onChatroomDisconnect(error) {
        console.log("ondisconnect", error);
    },
    /**
     * 收到消息
     */
    onChatroomMsgs(msgs) {
        console.log("onChatroomMsgs", msgs);
        let that = this;
        msgs.map(msg => {
            switch (msg.type) {
                case "notification": {
                    that.addNotificationToRender(msg);
                    break;
                }
                case "text": {
                    that.addTextToRender(msg);
                    break;
                }
            }
        });
        // 滚动到底部
        that.scrollToBottom();
    },
    /**
     * 添加通知消息到渲染队列中
     */
    addNotificationToRender(msg) {
        // 添加到渲染队列
        let {
            hallRoomId
        } = this.data;
        if (!msg.text) {
            return;
        }
        let msgData = {
            my: msg.from == app.globalData.account,
            account: msg.from,
            nick: msg.attach.fromNick,
            text: msg.text,
            type: msg.attach.type,
        }
        if (msg.chatroomId !== hallRoomId) {
            this.setData({
                smallNewsArr: [...this.data.smallNewsArr, msgData]
            });
        }
        if (msg.chatroomId == hallRoomId) {
            this.setData({
                hallNewsArr: [...this.data.hallNewsArr, msgData]
            });
        }
    },


    /**
     *  检测 人员流动
     */
    listenNetcallEvent() {
        let that = this;
        app.globalData.emitter.on("syncDone", data => {
            console.log("syncDone", data);
            console.error("updateUserlist---->", data.userlist);
            that.setData({
                userlist: data.userlist
            });
            that.reconnectStreamAfter();
        });
        app.globalData.emitter.on("clientLeave", data => {
            console.error("有人离开了，离开前：");
            console.error(that.data.userlist);
            setTimeout(() => {
                that.getRoomQueue();
            }, 500);
            that._personLeave(data);
            console.error("有人离开了，离开后：");
            console.error(that.data.userlist);
        });
        app.globalData.emitter.on("clientJoin", data => {
            setTimeout(() => {
                that.getRoomQueue();
            }, 500);
            that._personJoin(data);
            console.error(that.data.userlist);
        });
        app.globalData.emitter.on("joinChannel", data => {
            let userlist = Object.assign([], this.data.userlist);
            userlist.map(user => {
                if (user.account === data.account) {
                    user.uid = data.uid;
                }
            });
            that.setData({
                userlist
            });
        });
        // 信令准备重连
        app.globalData.emitter.on("willreconnect", () => {
            this.stopStream();
        });
    },
    _personJoin(data) {
        console.error("加入了", data);
        let updateUserlist = this.data.userlist;
        updateUserlist.push(data);
        this.setData({
            userlist: updateUserlist
        });
    },
    _personLeave(data) {
        let userlist = Object.assign([], this.data.userlist);
        userlist.map((user, index) => {
            if (user.uid === data.uid) {
                let player = this._getPlayerComponent(data.uid);
                if (player) {
                    player.stop();
                }
                user.url = "";
            }
        });
        this.setData({
            userlist
        });
    },

    /**
     * 心跳请求
     */
    getHeart() {
        let that = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
            company_uid: that.data.roomSource.company_uid
        };
        ajaxPost("/meeting/roomHeartbeat", data, res => {
            if (res.code == 0) {
                if (this.data.firstSource.uid !== res.data.first_uid) {
                    this.setData({
                        popupShow: false
                    })
                    this.getRoomQueue()
                }
                this.setData({
                    firstTime: res.data.time
                });
            } else {
                showToast("error", res.msg);
            }
        });
    },
    /**
     * 排队信息
     */
    getRoomQueue() {
        let that = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
            company_uid: that.data.roomSource.company_uid
        };
        ajaxPost("/meeting/roomQueue", data, res => {
            if (res.code == 0) {
                if (res.data.first_user.length !== 0) {
                    this.setData({
                        firstSource: res.data.first_user,
                        rankingSource: res.data.list,
                        firstTime: res.data.first_user.time
                    });
                } else {
                    this.setData({
                        firstSource: [],
                        rankingSource: [],
                        firstTime: 0
                    });
                }
            } else {
                showToast("error", res.msg);
            }
        });
    },
    /**
     * 推拉流
     */
    stopStream(duration = 1000) {
        if (this.stopStreamTimer) {
            clearTimeout(this.stopStreamTimer);
        }
        if (this.data.streamStoped) {
            return Promise.resolve();
        }
        console.log("停止推流");
        return new Promise((resolve, reject) => {
            this.stopStreamTimer = setTimeout(() => {
                if (!this.livePusherContext) {
                    return;
                }
                if (!this.livePlayerMap) {
                    this.livePlayerMap = {};
                }
                this.data.userlist.map(user => {
                    const uid = `${user.uid}`;
                    console.log(`停止拉流 ${uid}`);
                    if (!this.livePlayerMap[uid]) {
                        this.livePlayerMap[uid] = wx.createLivePlayerContext(
                            `yunxinplayer-${uid}`,
                            this
                        );
                    }
                    this.livePlayerMap[uid].stop();
                });
                this.livePusherContext.stop({
                    complete: () => {
                        console.log("推流已停止");
                        this.setData({
                            streamStoped: true
                        });
                        resolve();
                    }
                });
            }, duration);
        });
    },
    reconnectStream() {
        if (this.data.streamNeedReconnect) {
            clearTimeout(this.stopStreamTimer);
            console.log("开始推流");
            //    let asd = wx.createLivePusherContext()
            console.log("this.data.userlist---->", this.data.userlist);
            console.error(
                "this.livePusherContext---->",
                this.livePusherContext
            );
            this.livePusherContext.start({
                success: () => {
                    console.log("推流成功");
                    // this.setData({
                    //     streamStoped: false
                    // })
                },
                fail: () => {
                    console.log("推流失败");
                    // this.setData({
                    //     streamStoped: false
                    // })
                },
                complete: () => {
                    console.log("推流失败");
                    if (!this.livePlayerMap) {
                        this.livePlayerMap = {};
                    }
                    this.data.userlist.map(user => {
                        const uid = `${user.uid}`;
                        console.error(`重新播放 ${uid}`);
                        console.log(user);
                        if (!this.livePlayerMap[uid]) {
                            this.livePlayerMap[
                                uid
                            ] = wx.createLivePlayerContext(
                                `yunxinplayer-${uid}`,
                                this
                            );
                        }
                        this.livePlayerMap[uid].play();
                    });
                }
            });
        }
    },
    reconnectStreamAfter(duration = 0) {
        clearTimeout(this.reconnectStreamTimer);
        this.reconnectStreamTimer = setTimeout(() => {
            this.reconnectStream();
        }, duration);
    },

    /**
     *-- -- -- -- -- -- -- - > 页面操作逻辑<----------------------------
     */
    /**
     * 选择房间
     */
    selectRoom(e) {
        let type = e.currentTarget.dataset.type;
        if (this.data.selectRoomVal !== type) {
            this.setData({
                selectRoomVal: type
            });
        }
    },
    /**
     * 文本框输入事件
     */
    inputChange(e) {
        this.setData({
            inputValue: e.detail.value
        });
    },
    /**
     * 键盘单击发送，发送文本
     */
    inputSend(e) {
        this.setData({
            emojiShow: false,
        })
        this.sendRequest(this.data.inputValue);
    },
    /*
     * 发送网络请求：发送文本消息(包括emoji)
     */
    sendRequest(text) {
        let that = this;
        if (text == "") {
            showToast("text", "输入内容不能为空");
            return;
        }
        let Sender;
        if (this.data.selectRoomVal == "small") {
            Sender = app.globalData.smallRoom;
        } else {
            Sender = app.globalData.hallRoom;
        }
        Sender.sendText({
            text,
            done: (err, msg) => {
                if (err) {
                    console.log(err);
                    return;
                }
                that.setData({
                    inputValue: ""
                });
                // 刷新界面
                that.addTextToRender(msg);
                // 滚动到底部
                that.scrollToBottom();
            }
        });
    },
    /**
     * 添加文本(包含emoji)消息到渲染队列中
     */
    addTextToRender(msg) {
        // 刷新界面
        let {
            hallRoomId
        } = this.data;
        if (!msg.text) {
            return;
        }
        let msgData = {
            my: msg.from == app.globalData.account,
            account: msg.from,
            nick: msg.fromNick,
            text: msg.text,
            type: msg.type,
        }
        if (msg.chatroomId !== hallRoomId) {
            this.setData({
                smallNewsArr: [...this.data.smallNewsArr, msgData]
            });
        }
        if (msg.chatroomId == hallRoomId) {
            this.setData({
                hallNewsArr: [...this.data.hallNewsArr, msgData]
            });
        }

        this.scrollToBottom();
    },
    /**
     * 滚动聊天内容到底部
     */
    scrollToBottom: function () {
        var smallLen = this.data.smallNewsArr.length; //遍历的数组的长度
        var hallLen = this.data.hallNewsArr.length; //遍历的数组的长度
        if (this.data.selectRoomVal == "small") {
            this.setData({
                smallScrollTop: 1000 * smallLen,
            });
        } else {
            this.setData({
                hallScrollTop: 1000 * hallLen // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
            });
        }
    },


    /**
     * 查看简历图片
     */
    lookImg(e) {
        var current = e.target.dataset.src;
        this.setData({
            popupShow: false,
            lookImgShow: true,
            lookImgUrl: current
        })
        // let imgArr = [];
        // imgArr.push(this.data.studentSource.image);
        // wx.previewImage({
        //     current: current, // 当前显示图片的http链接
        //     urls: imgArr // 需要预览的图片http链接列表
        // });
    },
    /**
     * 简历图片下载
     */
    lookimgLoad() {
        var imgSrc = this.data.lookImgUrl
        wx.downloadFile({
            url: imgSrc,
            success: function (res) {
                console.log(res);
                //图片保存到本地
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function (data) {
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success',
                            duration: 2000
                        })
                    },
                    fail: function (err) {
                        console.log(err);
                        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                            console.log("当初用户拒绝，再次发起授权")
                            wx.openSetting({
                                success(settingdata) {
                                    console.log(settingdata)
                                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                        console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                                    } else {
                                        console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                                    }
                                }
                            })
                        }
                    },
                    complete(res) {
                        console.log(res);
                    }
                })
            }
        })
    },
    /**
     * 简历显示隐藏
     */
    lookimgSelect() {
        this.setData({
            popupShow: true,
            lookImgShow: !this.data.lookImgShow,
        })
    },
    /**
     * 
     * 简历信息保存
     */
    bindRemark(e) {
        this.setData({
            textareaVal: e.detail.value
        })
    },
    /**
     * 添加简历到简历库
     * 
     */
    addResume() {
        if (this.data.studentSource.is_add_resume == 1) {
            return;
        }
        let id = this.data.studentSource.user_id;
        let data = {
            remark: this.data.textareaVal,
            token: wx.getStorageSync("token"),
            user_id: id
        };
        ajaxPost("/company/pickResume", data, res => {
            if (res.code == 0) {
                let newstudentSource = this.data.studentSource
                newstudentSource.is_add_resume = 1
                this.setData({
                    studentSource: newstudentSource
                })
                showToast("text", '添加成功');
            } else {
                showToast("text", res.msg);
            }
        });
    },
    /**
     *  获取学生信息
     * @param {*} e 参数
     */
    clickStudentInfo(e) {
        let id = e.currentTarget.dataset.id;
        if (!id) {
            showToast('text', '当前位置没有人，请邀请后再试')
            return;
        }
        let data = {
            token: wx.getStorageSync("token"),
            user_id: id
        };
        ajaxPost("/authuser/resumeinfo", data, res => {
            console.log(res);
            if (res.code == 0) {
                this.setData({
                    textareaVal: res.data.remark,
                    popupShow: true,
                    studentSource: res.data
                });
            } else {
                showToast("text", res.msg);
            }
        });
    },

    /**
     * 弹窗关闭
     */
    companySelect(e) {
        let {
            textareaVal,
            studentSource,
        } = this.data
        if (studentSource.is_add_resume == 1 && textareaVal !== studentSource.remark) {
            let id = this.data.studentSource.user_id;
            console.error(this.data.studentSource);
            let data = {
                remark: this.data.textareaVal,
                token: wx.getStorageSync("token"),
                user_id: id
            };
            ajaxPost("/company/pickResume", data, res => {
                if (res.code == 0) {
                    showToast("text", '保存成功');
                } else {
                    showToast("text", res.msg);
                }
            });

        }
        this.setData({
            popupShow: false
        });
    },
    /**
     * 弹窗选择第几个显示
     * @param {穿参第几个} e
     */
    popupTitleSelect(e) {
        let index = e.currentTarget.dataset.index;
        if (this.popupVal !== index) {
            this.setData({
                popupVal: index
            });
        }
    },
    /**
     * 结束聊天
     */
    kick() {
        let {
            accid
        } = this.data.studentSource
        let that = this
        console.log(accid);
        app.globalData.smallRoom.getChatroom({
            done: getChatroomDone
        });

        function getChatroomDone(error, obj) {
            console.log('获取聊天室信息' + (!error ? '成功' : '失败'), error, obj);
        }
        app.globalData.smallRoom.kickChatroomMember({
            account: accid,
            done: kickChatroomMemberDone
        });

        function kickChatroomMemberDone(error, obj) {
            if (!error) {
                that.setData({
                    popupShow: false
                });
                showToast('text', '结束聊天成功', {
                    duration: 1000
                })
            } else {
                that.setData({
                    popupShow: false
                });
                showToast('text', '结束聊天失败，请重试', {
                    duration: 1000
                })
            }
            console.log('踢人' + (!error ? '成功' : '失败'), error, obj);
        }
    },
    /**
     * 输入框和操作按钮切换
     */
    footetControl() {
        this.setData({
            footerShow: !this.data.footerShow,
            emojiShow: false
        })
    },
    /**
     * 企业发送信息给大厅里面
     */
    lobbyInvite() {
        let that = this
        if (this.data.lobbyInviteTime !== 0) {
            return;
        }
        var content = {
            type: 'company',
            nick: this.data.roomSource.company_name,
            text: `大家快点击进入${this.data.roomSource.company_name}的房间吧，HR等你哟～`,
            account: this.data.roomSource.company_logo,
        };
        app.globalData.hallRoom.sendCustomMsg({
            content: JSON.stringify(content),
            done: sendChatroomMsgDone
        });

        function sendChatroomMsgDone(error, msg) {
            console.log('发送聊天室' + msg.type + '消息' + (!error ? '成功' : '失败') + ', id=' + msg.idClient, error, msg);
            if (!error) {
                that.setData({
                    hallNewsArr: [...that.data.hallNewsArr, content],
                    lobbyInviteTime: 600
                });
                clearInterval(that.setLobbyInviteTime);
                that.setLobbyInviteTime = setInterval(() => {
                    that.setData({
                        lobbyInviteTime: that.data.lobbyInviteTime - 1
                    })
                }, 1000);
                that.scrollToBottom();
                showToast('text', '已发送大厅推广消息')
            } else {
                showToast('text', '发送失败，请退出房间重试')
            }
        }
    },
    /**
     * 增加时间
     */
    addTime() {
        let that = this
        if (this.data.firstSource == 0) {
            showToast('text', '暂时没有正在面试的学生哦，快去邀请他们吧')
            return;
        }
        let data = {
            token: wx.getStorageSync('token'),
            user_id: this.data.firstSource.uid,
            time: 60,
            meeting_id: this.data.contId,
        }
        ajaxPost('/meeting/addtime', data, (res) => {
            if (res.code == 0) {
                var content = {
                    type: 'company',
                    nick: this.data.roomSource.company_name,
                    text: '我想再深入了解一下，给你延长了1分钟的时间',
                    account: this.data.roomSource.company_logo,
                };
                app.globalData.smallRoom.sendCustomMsg({
                    content: JSON.stringify(content),
                    done: sendChatroomMsgDone
                });

                function sendChatroomMsgDone(error, msg) {
                    showToast('text', '加时成功');
                    that.scrollToBottom();
                    that.setData({
                        smallNewsArr: [...that.data.smallNewsArr, content],
                    });

                }
            } else {
                showToast('text', res.msg)
            }
        })

    },
    /**
     * 麦克风控制
     */
    microphoneControl() {
        if (!this.data.muted) {
            showToast('text', '麦克风已打开 ')
        } else {
            showToast('text', '麦克风已关闭 ')

        }
        this.setData({
            muted: !this.data.muted
        })
    },
    /**
     * 隐私公开切换
     */
    privacySwitchover() {
        let that = this
        if (this.data.privacyVal) {
            var content = {
                type: 'company',
                privacyVal: 2,
                nick: this.data.roomSource.company_name,
                text: '我有几个隐私问题要问这位同学，大家将暂时听不见我们的谈话，请大家稍等一下～',
                account: this.data.roomSource.company_logo,
            };
            app.globalData.smallRoom.sendCustomMsg({
                content: JSON.stringify(content),
                done: sendChatroomMsgDone
            });

            function sendChatroomMsgDone(error, msg) {
                showToast('text', `已切换成隐私模式`)
                that.getPricacy(false)
                that.scrollToBottom();
                that.setData({
                    smallNewsArr: [...that.data.smallNewsArr, content],
                });
            }
        } else {
            var content = {
                type: 'company',
                privacyVal: 1,
                nick: this.data.roomSource.company_name,
                text: '我们已经结束隐私谈话了',
                account: this.data.roomSource.company_logo,
            };
            app.globalData.smallRoom.sendCustomMsg({
                content: JSON.stringify(content),
                done: sendChatroomMsgDone
            });

            function sendChatroomMsgDone(error, msg) {
                showToast('text', '已切换成公开模式');
                that.getPricacy(true)
                that.scrollToBottom();
                that.setData({
                    smallNewsArr: [...that.data.smallNewsArr, content],
                });
            }
        }
        this.setData({
            privacyVal: !this.data.privacyVal
        })
    },
    getPricacy(type) {
        console.error(type);
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: this.data.contId,
            company_uid: 0,
            is_hide: type ? 1 : 2
        }
        ajaxPost('/meeting/setVroomId', data, res => {
            console.error(res);
            if (res.code == 0) {} else {

            }

        })
    },
    /**
     * 播放音频控制
     */
    voiceControl() {
        let that = this;
        if (this.data.playVoice) {
            showToast('text', `播放声音已打开`)
        } else {
            showToast('text', `播放声音已关闭`)
        }
        this.setData({
            playVoice: !this.data.playVoice
        })
    },
    /**
     * 暂未完善
     */
    maintain() {
        showToast('text', '正在努力开发中，请等待后续版本更新。')
    },
    /**
     * 表情添加
     */
    emojiAdd(e) {
        console.log('hall', e);
        this.setData({
            inputValue: this.data.inputValue + e.detail.emoji
        })
    },
    /**
     * 表情显示隐藏控制
     */
    emojiClick() {
        this.setData({
            emojiShow: !this.data.emojiShow
        })
    },
    /**
     * 控制其他房间展示
     */
    selectcompanyListShow(e) {
        if (e.currentTarget.dataset.show == 'true') {
            this.setData({
                companyListShow: true
            })
            this.getStudentList();
            // this.getRoomInfo();
        } else {
            this.setData({
                companyListShow: false
            })
        }
    },
    /**
     * 获取当前会场信息
     */
    getRoomInfo() {
        let that = this
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
        };
        ajaxPost("/meeting/meetinginfo", data, res => {
            if (res.code == 0) {
                that.setData({
                    companyListSource: res.data.company_total,
                })
                return;
            }
            showToast('text', res.msg)

        });
    },
    /**
     * 学生列表 和 企业列表 切换
     */
    restsSwitch(e) {
        let type = e.currentTarget.dataset.type;
        if (type == 'company') {
            this.setData({
                restsShow: true
            })
            this.getStudentList()
        } else {
            this.setData({
                restsShow: false
            })
            this.getRoomInfo();
        }

    },
    /**
     * 获取大厅学生列表
     */
    getStudentList() {
        let that = this
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
        };
        ajaxPost("/meeting/hallUserList", data, res => {
            if (res.code == 0) {
                that.setData({
                    studentListSource: res.data.list,
                })
                return;
            }
            showToast('text', res.msg)

        });
    },
    /**
     * 邀请学生
     */
    inviteStudent(e) {
        let index = e.currentTarget.dataset.index,
            that = this,
            type = e.currentTarget.dataset.type,
            studentListSource = this.data.studentListSource
        console.log(e);
        if (this.data.rankingSource.length >= 9) {
            showToast('text', '您的房间以爆满，请稍后再试');
            return;
        }
        if (studentListSource.length == 0) {
            showToast('text', '大厅暂无学生，请稍后再试');
            return;
        }
        if (type == 'all') {
            if (!app.globalData.inviteVal) {
                return;
            }
            for (const key in studentListSource) {
                studentListSource[key].is_invitation = 1
            }
            app.globalData.inviteVal = !app.globalData.inviteVal
            that.setData({
                inviteVal: app.globalData.inviteVal
            })
            setTimeout(() => {
                app.globalData.inviteVal = !app.globalData.inviteVal
                that.setData({
                    inviteVal: app.globalData.inviteVal
                })
            }, 600000);
            this.getInvitation(0)
        }
        if (type == "alone") {
            if (studentListSource[index].is_invitation == 1) {
                return;
            }
            studentListSource[index].is_invitation = 1
            this.getInvitation(studentListSource[index].uid)
        }
        var content = {
            type: 'invite',
            nick: this.data.roomSource.company_name,
            company_uid: this.data.roomSource.company_uid,
            accid: type == 'all' ? 0 : studentListSource[index].accid,
        };
        app.globalData.hallRoom.sendCustomMsg({
            content: JSON.stringify(content),
            done: sendChatroomMsgDone
        });

        function sendChatroomMsgDone(error, msg) {
            console.log('发送聊天室' + msg.type + '消息' + (!error ? '成功' : '失败') + ', id=' + msg.idClient, error, msg);
            if (!error) {
                that.setData({
                    studentListSource: studentListSource
                })
                showToast('text', '邀请成功', {
                    isMask: true,
                    duration: 2000,
                });
            } else {
                showToast('text', '发送失败，请退出房间重试')
            }
        }
    },
    /**
     * 邀请请求
     */
    getInvitation(id) {
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: this.data.contId,
            user_ids: id,
        }
        ajaxPost('/meeting/meetingInvitation', data, res => {})
    }
    // /**
    //  * 房间分享
    //  */
    // onShareAppMessage() {
    //     let {
    //         companyId,
    //         contId,
    //         hallRoomId,
    //         roomSource
    //     } = this.data
    //     return {
    //         title: `我正在与${roomSource.company_name}hr语音直聊，快来跟我一起吧`,
    //         imageUrl: 'https://xiaozhao.shuzhi.group/wxapp/img_room_share2.png',
    //         path: `/pages/shareLogin/shareLogin?type=shareSmall&hallId=${contId}&hallRoomId=${hallRoomId}&companyId=${companyId}`,
    //         success: function (res) {
    //             showToast('text', '分享成功')
    //         }
    //     }
    // },
});